import os

from PyQt4 import QtGui, QtCore

from notificator import Notificator

class Preferences(QtGui.QDialog):
    
    hostings = {'All':0, 'Megaupload':3, 'Rapidshare':1, 'Hotfile':27, 'Mediafire':15}

    def __init__(self, parent, notifi, tdb):
        QtGui.QWidget.__init__(self, parent)
        self._notif = notifi
        self._db = tdb
        self._lang = parent.lang
        self.setWindowTitle(self._lang['preferences'])
        self.setWindowIcon(self.style().standardIcon(QtGui.QStyle.SP_FileDialogListView))

        #Load configuration
        self._config = self._db.read_configuration()

        v_box = QtGui.QVBoxLayout(self)
        #Notification Configuration
        self._check = QtGui.QCheckBox(self._lang['maintain'])
        if self._config[0] == 1:
            self._check.setChecked(True)
        v_box2 = QtGui.QVBoxLayout()
        v_box2.setMargin(5)
        self._radio1 = QtGui.QRadioButton(self._lang['notiDay'])
        self._radio2 = QtGui.QRadioButton(self._lang['notiDayAf'])
        v_box2.addWidget(self._radio1)
        v_box2.addWidget(self._radio2)
        h_box1 = QtGui.QHBoxLayout()
        self._label = QtGui.QLabel('')
        self._dial = QtGui.QDial()
        self._dial.setMaximum(24)
        self._dial.setMinimum(1)
        self._dial.setNotchesVisible(True)
        h_box1.addWidget(self._label)
        h_box1.addWidget(self._dial)
        h_box1.setMargin(5)
        h_box2 = QtGui.QHBoxLayout()
        #Save-Cancel Buttons
        self._save = QtGui.QPushButton(self._lang['save'])
        self._cancel = QtGui.QPushButton(self._lang['cancel'])
        h_box2.addWidget(self._cancel)
        h_box2.addWidget(self._save)
        #Download Configuration
        v_download = QtGui.QVBoxLayout()
        self._checkIcon = QtGui.QCheckBox(self._lang['icon'])
        self._checkDownload = QtGui.QCheckBox(self._lang['downEpi'])
        if self._config[3] == 1:
            self._checkDownload.setChecked(True)
        if self._config[5] == 1:
            self._checkIcon.setChecked(True)
        self._checkTorrent = QtGui.QCheckBox('Torrent')
        self._checkDirect = QtGui.QCheckBox('Direct Download')
        self._checkTorrent.setEnabled(self._checkDownload.isChecked())
        self._checkDirect.setEnabled(self._checkDownload.isChecked())
        if self._config[4] == 1:
            self._checkDirect.setChecked(True)
            self._checkTorrent.setChecked(False)
        else:
            self._checkTorrent.setChecked(True)
            self._checkDirect.setChecked(False)
        h_dirtor = QtGui.QHBoxLayout()
        h_dirtor.addWidget(self._checkTorrent)
        h_dirtor.addWidget(self._checkDirect)
        self._comboHosting = QtGui.QComboBox()
        self._comboHosting.setEnabled(self._checkDownload.isChecked() and self._checkDirect.isChecked())
        listHosts = [k for k in Preferences.hostings.keys()]
        self._comboHosting.addItems(listHosts)
        h_host = QtGui.QHBoxLayout()
        h_host.addWidget(QtGui.QLabel(self._lang['from']))
        h_host.addWidget(self._comboHosting)
        listFormats = ['All', 'rar', 'avi', 'rmvb', 'mpg', 'mpeg', 'mkv']
        self._comboFormats = QtGui.QComboBox()
        self._comboFormats.addItems(listFormats)
        self._comboFormats.setEnabled(self._checkDownload.isChecked() and self._checkDirect.isChecked())
        h_format = QtGui.QHBoxLayout()
        h_format.addWidget(QtGui.QLabel(self._lang['format']))
        h_format.addWidget(self._comboFormats)
        v_download.addWidget(self._checkIcon)
        v_download.addWidget(self._checkDownload)
        v_download.addLayout(h_dirtor)
        v_download.addLayout(h_host)
        v_download.addLayout(h_format)
        #Radio Buttons Configuration
        if self._config[1] == 0:
            self._radio1.setChecked(True)
            self._notify_on_day_change()
        else:
            self._radio2.setChecked(True)
        #Set selected in combo
        items = Preferences.hostings.items()
        pos = [i for i in range(len(items)) if items[i][1] == self._config[6]]
        self._comboHosting.setCurrentIndex(pos[0])
        self._comboFormats.setCurrentIndex(listFormats.index(self._config[7]))
            
        #Add Widgets and Layout
        v_box.addWidget(self._check)
        v_box.addLayout(v_box2)
        v_box.addLayout(h_box1)
        v_box.addLayout(v_download)
        v_box.addLayout(h_box2)

        self.connect(self._dial, QtCore.SIGNAL("valueChanged(int)"), self._value_changed)
        self.connect(self._save, QtCore.SIGNAL("clicked()"), self._save_config)
        self.connect(self._cancel, QtCore.SIGNAL("clicked()"), self.hide)
        self.connect(self._radio1, QtCore.SIGNAL("clicked()"), self._notify_on_day_change)
        self.connect(self._radio2, QtCore.SIGNAL("clicked()"), self._notify_on_day_after_change)
        self.connect(self._checkDownload, QtCore.SIGNAL("clicked()"), self._activate_download_episodes)
        self.connect(self._checkTorrent, QtCore.SIGNAL("clicked()"), lambda: self._changed_direct_torrent(True))
        self.connect(self._checkDirect, QtCore.SIGNAL("clicked()"), lambda: self._changed_direct_torrent(False))
        self._dial.setValue(self._config[2])

    def _value_changed(self):
        self._label.setText(self._lang['noti']+ str(self._dial.value()) + self._lang['hr'])
        
    def _changed_direct_torrent(self, value):
        self._checkTorrent.setChecked(value)
        self._checkDirect.setChecked(not value)
        self._comboHosting.setEnabled(not value)
        self._comboFormats.setEnabled(not value)
        
    def _activate_download_episodes(self):
        if self._checkDownload.isChecked():
            self._checkTorrent.setEnabled(True)
            self._checkDirect.setEnabled(True)
        else:
            self._checkTorrent.setEnabled(False)
            self._checkDirect.setEnabled(False)
        self._comboHosting.setEnabled(self._checkDownload.isChecked() and self._checkDirect.isChecked())
        self._comboFormats.setEnabled(self._checkDownload.isChecked() and self._checkDirect.isChecked())
        
    def _notify_on_day_change(self):
        self._checkDownload.setChecked(False)
        self._checkDownload.setEnabled(False)
        self._checkTorrent.setEnabled(False)
        self._checkDirect.setEnabled(False)
        self._comboHosting.setEnabled(False)
        self._comboFormats.setEnabled(False)

    def _notify_on_day_after_change(self):
        self._checkDownload.setEnabled(True)

    def _save_config(self):
        host = str(Preferences.hostings[str(self._comboHosting.currentText())]) if self._checkDirect.isChecked() else '0'
        values = str(int(self._check.isChecked())) + ', ' + str(int(self._radio2.isChecked())) + ', '\
             + str(self._dial.value()) + ', ' + str(int(self._checkDownload.isChecked())) + ', '\
             + str(int(self._checkDirect.isChecked())) + ', '\
             + str(int(self._checkIcon.isChecked())) + ', ' + host + ', "' + str(self._comboFormats.currentText()) + '"'
        self._db.save_configuration(values)
        
        self._notif.set_new_configuration(self._dial.value(), int(self._radio1.isChecked()), 
                int(self._checkDownload.isChecked()),
                int(self._checkIcon.isChecked()), int(self._checkDirect.isChecked()),
                Preferences.hostings[str(self._comboHosting.currentText())], str(self._comboFormats.currentText()))
        if not self._checkIcon.isChecked():
            imageList = os.listdir(self._db.dire)
            for i in imageList:
                if i != 'pytv.dat' and i != 'plugins':
                    os.remove(self._db.dire + i)
        self.hide()

    def closeEvent(self, event):
        event.ignore()
        self.done(0)
